package com.igeek.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igeek.boot.entity.ContractTemplates;
import com.igeek.boot.mapper.ContractTemplatesMapper;
import com.igeek.boot.service.IContractTemplatesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.boot.utils.QiniuUtils;
import com.igeek.boot.vo.PageQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jwj
 * @since 2023-12-26
 */
@Slf4j
@Service
public class ContractTemplatesServiceImpl extends ServiceImpl<ContractTemplatesMapper, ContractTemplates> implements IContractTemplatesService {
    @Override
    @Transactional(readOnly = true)
    public Page<ContractTemplates> findPage(PageQueryVO pageQueryVO) {
        //获取分页条件
        Integer currentPage = pageQueryVO.getCurrentPage();
        Integer pageSize = pageQueryVO.getPageSize();
        Page<ContractTemplates> page = new Page<>(currentPage, pageSize);

        //封装查询条件  查询的信息可能根据仓库名称、仓库类型、仓库的城市进行查询
        LambdaQueryWrapper<ContractTemplates> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String queryString = pageQueryVO.getQueryString();
        lambdaQueryWrapper.or().like(StringUtils.hasLength(queryString), ContractTemplates::getTemplateName, queryString)
                .or().like(StringUtils.hasLength(queryString), ContractTemplates::getTemplateType, queryString);

        //执行查询
        Page<ContractTemplates> warehousesPage = baseMapper.selectPage(page, lambdaQueryWrapper);
        log.info("查询合同表的数据{}",warehousesPage.getRecords());
        return warehousesPage;
    }

    //上传文件
    @Override
    public String upload(MultipartFile file) throws IOException {
        if(file!=null){
            String oldName = file.getOriginalFilename();
            if(StringUtils.hasLength(oldName)) {
                String newName = "TEMPLATE_"+UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
                log.info("newName{}", newName);
                String upName = QiniuUtils.uploadForQiniu(file.getInputStream(), newName);
                return upName;
            }
        }
        return null;
    }

    @Override
    public boolean addTemplates(ContractTemplates templates) {
        templates.setCreateTime(LocalDateTime.now());
        int insert = baseMapper.insert(templates);
        if(insert>0) {
            return true;
        }
        return false;
    }


}
